<script setup lang="ts" name="PermissionForm">
import { ref, reactive, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Permission, PermissionCreateRequest, PermissionUpdateRequest } from '@/model/user-role-model'
import { createPermission, updatePermission, getPermissions } from '@/request/user-role-api'
import { MenuType } from '@/model/user-role-model'

const props = defineProps<{
  visible: boolean
  title: string
  permission?: Permission | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'saved'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<Partial<PermissionCreateRequest & PermissionUpdateRequest>>({
  id: 0,
  name: '',
  url: '',
  method: '',
  parent_id: null,
  level: 1,
  order: 0,
  icon: '',
  is_menu: MenuType.MENU
})

// 父级权限选项
const parentOptions = ref<{ label: string; value: number }[]>([])

// 获取父级权限列表
const fetchParentPermissions = async () => {
  try {
    const res = await getPermissions()
    if (res.code === 0 && res.data) {
      // 只有一级菜单和二级菜单可以作为父级
      parentOptions.value = res.data
        .filter(item => item.level <= 1) // 只有一级菜单可以作为父级
        .map(item => ({
          label: item.name,
          value: item.id
        }))
    }
  } catch (error) {
    console.error('获取父级权限出错：', error)
  }
}

// 表单校验规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  url: [
    { max: 200, message: 'URL不能超过 200 个字符', trigger: 'blur' }
  ],
  method: [
    { max: 10, message: '方法不能超过 10 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择菜单级别', trigger: 'change' },
    { type: 'number', min: 1, max: 2, message: '菜单级别必须是 1 或 2', trigger: 'change' }
  ],
  order: [
    { type: 'number', message: '排序必须是数字', trigger: 'change' }
  ],
  icon: [
    { max: 50, message: '图标不能超过 50 个字符', trigger: 'blur' }
  ]
})

// 监听父权限变化，自动设置级别
watch(() => formData.parent_id, (newVal) => {
  if (newVal) {
    formData.level = 2 // 有父级则为二级菜单
  } else {
    formData.level = 1 // 没有父级则为一级菜单
  }
}, { immediate: true })

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        
        if (props.permission) {
          // 更新权限
          const updateData: PermissionUpdateRequest = {
            id: props.permission.id,
            name: formData.name || '',
            url: formData.url,
            method: formData.method,
            parent_id: formData.parent_id,
            level: formData.level,
            order: formData.order,
            icon: formData.icon,
            is_menu: formData.is_menu
          }
          res = await updatePermission(props.permission.id, updateData)
        } else {
          // 创建权限
          const createData: PermissionCreateRequest = {
            name: formData.name || '',
            url: formData.url,
            method: formData.method,
            parent_id: formData.parent_id,
            level: formData.level || 1,
            order: formData.order || 0,
            icon: formData.icon,
            is_menu: formData.is_menu !== undefined ? formData.is_menu : MenuType.MENU
          }
          res = await createPermission(createData)
        }
        
        if (res.code === 0) {
          ElMessage.success(props.permission ? '更新成功' : '创建成功')
          closeDialog()
          emit('saved')
        } else {
          ElMessage.error(res.errorMsg || (props.permission ? '更新失败' : '创建失败'))
        }
      } catch (error) {
        console.error(props.permission ? '更新权限出错：' : '创建权限出错：', error)
        ElMessage.error(props.permission ? '更新失败' : '创建失败')
      }
    }
  })
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false)
  resetForm()
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重置为默认值
  formData.id = 0
  formData.name = ''
  formData.url = ''
  formData.method = ''
  formData.parent_id = null
  formData.level = 1
  formData.order = 0
  formData.icon = ''
  formData.is_menu = MenuType.MENU
}

// 菜单级别选项
const levelOptions = [
  { label: '一级菜单', value: 1 },
  { label: '二级菜单', value: 2 }
]

// 菜单类型选项
const menuTypeOptions = [
  { label: '菜单项', value: MenuType.MENU },
  { label: '按钮/操作', value: MenuType.BUTTON }
]

// HTTP方法选项
const methodOptions = [
  { label: 'GET', value: 'GET' },
  { label: 'POST', value: 'POST' },
  { label: 'PUT', value: 'PUT' },
  { label: 'DELETE', value: 'DELETE' },
  { label: 'PATCH', value: 'PATCH' }
]

// 监听权限数据变化
watch(
  () => props.permission,
  (newVal) => {
    if (newVal) {
      formData.id = newVal.id
      formData.name = newVal.name
      formData.url = newVal.url || ''
      formData.method = newVal.method || ''
      formData.parent_id = newVal.parent_id || null
      formData.level = newVal.level
      formData.order = newVal.order
      formData.icon = newVal.icon || ''
      formData.is_menu = newVal.is_menu
    } else {
      resetForm()
    }
  },
  { immediate: true }
)

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      fetchParentPermissions()
    }
  },
  { immediate: true }
)
</script>

<template>
  <el-dialog
    :title="title"
    :model-value="visible"
    @update:model-value="(val) => emit('update:visible', val)"
    :close-on-click-modal="false"
    width="550px"
    @closed="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      label-position="right"
    >
      <el-form-item label="权限名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入权限名称" />
      </el-form-item>
      
      <el-form-item label="父级权限" prop="parent_id">
        <el-select 
          v-model="formData.parent_id" 
          placeholder="请选择父级权限" 
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in parentOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value ? item.value : 0"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="菜单级别" prop="level">
        <el-radio-group v-model="formData.level">
          <el-radio :label="1">一级菜单</el-radio>
          <el-radio :label="2">二级菜单</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="菜单类型" prop="is_menu">
        <el-radio-group v-model="formData.is_menu">
          <el-radio :label="MenuType.MENU">菜单项</el-radio>
          <el-radio :label="MenuType.BUTTON">按钮/操作</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="URL" prop="url">
        <el-input v-model="formData.url" placeholder="请输入URL，如/system/users" />
      </el-form-item>
      
      <el-form-item label="HTTP方法" prop="method">
        <el-select 
          v-model="formData.method" 
          placeholder="请选择HTTP方法" 
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in methodOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="图标" prop="icon">
        <el-input v-model="formData.icon" placeholder="请输入菜单图标" />
      </el-form-item>
      
      <el-form-item label="排序" prop="order">
        <el-input-number v-model="formData.order" :min="0" :max="999" style="width: 100%" />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
